var util = require('../../utils/util.js');
var api = require('../../config/api.js');
var user = require('../../utils/user.js');

var app = getApp();

Page({
  data: {
    cartGoods: [],
    cartTotal: {
      "goodsCount": 0,
      "goodsAmount": 0.00,
      "checkedGoodsCount": 0,
      "checkedGoodsAmount": 0.00
    },
    isEditCart: false,
    checkedAllStatus: true,
    editCartList: [],
    hasLogin: false
  },
  onLoad: function(options) {
    // 页面初始化 options为页面跳转所带来的参数

  },
  onReady: function() {
    // 页面渲染完成

  },  
  onPullDownRefresh() {
    if(app.globalData.hasLogin){
      // 页面显示
      wx.showLoading({
        title: '加载中...',
      });
      //wx.showNavigationBarLoading() //在标题栏中显示加载
      this.getCartList(); 
      //wx.hideNavigationBarLoading() //完成停止加载
      wx.stopPullDownRefresh() //停止下拉刷新
    }
  },  
  onShow: function() {
    // 页面显示
    if (app.globalData.hasLogin) {
      // 页面显示
      wx.showLoading({
        title: '加载中...',
      });
      this.getCartList();
    }     
    this.setData({
      hasLogin: app.globalData.hasLogin
    });
  },
  onHide: function() {
    // 页面隐藏
  },
  onUnload: function() {
    // 页面关闭
  },
  goLogin() {
    wx.navigateTo({
      url: "/pages/auth/login/login"
    });
  },
  getCartList: function() {
    let that = this;
    util.request(api.CartList).then(function(res) {
      if (res.code === 200) {
        var _cartGoods= res.dataObject;
        var _checkedGoodsCount = 0;
        var _goodsAmount = 0;
        var _checkedGoodsAmount = 0;  

        for (let index = 0; index < _cartGoods.length; index++) {
          const element = _cartGoods[index];
          let _skuPrice = element.skuPrice;
          let _cartChecked = element.cartChecked;
          let skuCount = element.skuCount;
          if(_cartChecked===2){
            element.checked = false;
          }   
          let checked = element.checked;
          if(checked===true){ 
            _checkedGoodsCount = _checkedGoodsCount + 1;
            _checkedGoodsAmount = _checkedGoodsAmount + (_skuPrice * skuCount);
          } 
          _goodsAmount = _goodsAmount + _skuPrice;
          let _attrSkuJson = element.attrSkuJson;
          let _attrSkuAry = JSON.parse(_attrSkuJson); 
          var _skuSpecStr = "";
          if(_attrSkuAry.length>0){
            for (let index2 = 0; index2 < _attrSkuAry.length; index2++) {
              const element2 = _attrSkuAry[index2]; 
              if(index2>0){ 
                _skuSpecStr = _skuSpecStr +" , ";
              }
              _skuSpecStr = _skuSpecStr + element2.titleName;
              _skuSpecStr = _skuSpecStr +"："+ element2.attrName;
            }
          }
          element.specStr = _skuSpecStr;
        }
        var _cartTotal = {
          goodsCount:_cartGoods.length,
          checkedGoodsCount:_checkedGoodsCount,
          goodsAmount:_goodsAmount,
          checkedGoodsAmount:_checkedGoodsAmount,
        };
        
        that.setData({
          cartGoods: _cartGoods,
          cartTotal: _cartTotal,
        });

        that.setData({
          checkedAllStatus: that.isCheckedAll()
        });
      }else{
        var _cartTotal = {
          goodsCount:0,
          checkedGoodsCount:0,
          goodsAmount:0,
          checkedGoodsAmount:0,
        };

        that.setData({
          cartGoods: [],
          cartTotal: _cartTotal,
        });
      }
      wx.hideLoading();
    });
  },
  isCheckedAll: function() {
    //判断购物车商品已全选
    return this.data.cartGoods.every(function(element, index, array) {
      if (element.checked == true) {
        return true;
      } else {
        return false;
      }
    });
  },
  doCheckedAll: function() {
    let checkedAll = this.isCheckedAll()
    this.setData({
      checkedAllStatus: this.isCheckedAll()
    });
  },
  checkedItem: function(event) {
    let itemIndex = event.target.dataset.itemIndex;
    let that = this;

    let _cartId = that.data.cartGoods[itemIndex].id;
    let _cartChecked = that.data.cartGoods[itemIndex].checked ? 2 : 1;
    if (!this.data.isEditCart) {
      util.request(api.CartChecked, {
        cartId: _cartId,
        cartChecked:_cartChecked 
      }, 'POST').then(function(res) {
        if (res.code === 200) {
          that.getCartList();
          // that.setData({
          //   cartGoods: res.data.cartList,
          //   cartTotal: res.data.cartTotal
          // });
        }
        that.setData({
          checkedAllStatus: that.isCheckedAll()
        });
      });
    } else {
      //编辑状态
      let tmpCartData = this.data.cartGoods.map(function(element, index, array) {
        if (index == itemIndex) {
          element.checked = !element.checked;
        }

        return element;
      });
      that.setData({
        cartGoods: tmpCartData,
        checkedAllStatus: that.isCheckedAll(),
        'cartTotal.checkedGoodsCount': that.getCheckedGoodsCount()
      });
    }
  },
  getCheckedGoodsCount: function() {
    var checkedGoodsCount = 0;  
    this.data.cartGoods.forEach(function(v) {
      if (v.checked === true) {
        checkedGoodsCount += v.skuCount;
      }
    }); 
    return checkedGoodsCount;
  },
  checkedAll: function() {
    let that = this;

    if (!this.data.isEditCart) {
      var productIds = this.data.cartGoods.map(function(v) {
        return v.productId;
      });
      util.request(api.CartChecked, {
        productIds: productIds,
        isChecked: that.isCheckedAll() ? 0 : 1
      }, 'POST').then(function(res) {
        if (res.errno === 0) {
          console.log(res.data);
          that.setData({
            cartGoods: res.data.cartList,
            cartTotal: res.data.cartTotal
          });
        }

        that.setData({
          checkedAllStatus: that.isCheckedAll()
        });
      });
    } else {
      //编辑状态
      let checkedAllStatus = that.isCheckedAll();
      let tmpCartData = this.data.cartGoods.map(function(v) {
        v.checked = !checkedAllStatus;
        return v;
      });

      that.setData({
        cartGoods: tmpCartData,
        checkedAllStatus: that.isCheckedAll(),
        'cartTotal.checkedGoodsCount': that.getCheckedGoodsCount()
      });
    }
    
  },
  editCart: function() {
    var that = this;
    if (this.data.isEditCart) {
      this.getCartList();
      this.setData({
        isEditCart: !this.data.isEditCart
      });
    } else {
      //编辑状态
      let tmpCartList = this.data.cartGoods.map(function(v) {
        v.checked = false;
        return v;
      });
      this.setData({
        editCartList: this.data.cartGoods,
        cartGoods: tmpCartList,
        isEditCart: !this.data.isEditCart,
        checkedAllStatus: that.isCheckedAll(),
        'cartTotal.checkedGoodsCount': that.getCheckedGoodsCount()
      });
    }

  },
  updateCart: function(cartId, number) {
    let that = this;
    util.request(api.CartUpdate, {
      cartId: cartId,
      number: number
    }, 'POST').then(function(res) {
      that.setData({
        checkedAllStatus: that.isCheckedAll()
      });
    });
  },

  cutNumber: function(event) {
    let itemIndex = event.target.dataset.itemIndex;
    let cartItem = this.data.cartGoods[itemIndex];
    let number = (cartItem.skuCount - 1 > 1) ? cartItem.skuCount - 1 : 1;
    cartItem.skuCount = number; 
    this.setData({
      cartGoods: this.data.cartGoods
    });
    this.updateCart(cartItem.id, number);
  },  
  
  addNumber: function(event) {
    let itemIndex = event.target.dataset.itemIndex;
    let cartItem = this.data.cartGoods[itemIndex];
    let number = cartItem.skuCount + 1;
    cartItem.skuCount = number; 
    this.setData({
      cartGoods: this.data.cartGoods
    });
    this.updateCart(cartItem.id,number);

  },
  checkoutOrder: function() {
    //获取已选择的商品
    let that = this;

    var checkedGoods = this.data.cartGoods.filter(function(element, index, array) {
      if (element.checked == true) {
        return true;
      } else {
        return false;
      }
    });

    if (checkedGoods.length <= 0) {
      return false;
    }

    // storage中设置了cartId，则是购物车购买
    try {
      wx.setStorageSync('cartId', 0);
      wx.navigateTo({
        url: '/pages/checkout/checkout'
      })
    } catch (e) {}

  },
  deleteCart: function() {
    //获取已选择的商品
    let that = this;

    let _cartIds = this.data.cartGoods.filter(function(element, index, array) {
      if (element.checked == true) {
        return true;
      } else {
        return false;
      }
    });

    if (_cartIds.length <= 0) {
      return false;
    }

    _cartIds = _cartIds.map(function(element, index, array) {
      if (element.checked == true) {
        return element.id;
      }
    });

    util.request(api.CartDelete, {
      cartIds: _cartIds
    }, 'POST').then(function(res) {
      if (res.code === 200) {
          that.getCartList();
        // let cartList = res.data.cartList.map(v => {
        //   v.checked = false;
        //   return v;
        // });

        // that.setData({
        //   cartGoods: cartList,
        //   cartTotal: res.data.cartTotal
        // });
      } 
      that.setData({
        checkedAllStatus: false
      });
    });
  }
})